<?php

namespace App\Admin\Controllers;

use App\Models\QdcsConfig;

use com_jjcbs\lib\ServiceFactory;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;
use ext\service\ConfigServiceImpl;

class ConfigController extends Controller
{
    use ModelForm;

    private $configService;
    public function __construct()
    {
        $this->configService = ServiceFactory::getInstance(ConfigServiceImpl::class);
    }

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header('配置管理');
            $content->description('管理配置创建、删除、修改、查看');

            $content->body($this->grid());
        });
    }

    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header('编辑配置');
            $content->description('编辑全局配置、创建模板变量管理');

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header('创建管理');
            $content->description('创建全局配置、创建模板变量管理');

            $content->body($this->form());
        });
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Admin::grid(QdcsConfig::class, function (Grid $grid) {

            $grid->id('编号')->sortable();
            $grid->title('名称');
            $grid->config_key('配置键');
            $grid->config_val('配置值');
            $grid->created_at('创建时间');
            $grid->updated_at('更新时间');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Admin::form(QdcsConfig::class, function (Form $form) {
            $form->text('title' , '名称')->rules('required');
            $form->text('config_key' , '配置项键')->rules('required');
            $form->text('config_val' , '配置项值')->rules('required');
        });
    }

    public function destroy($id)
    {
        try{
            $this->configService->delById($id);
            return response()->json([
                'status'  => true,
                'message' => trans('admin::lang.delete_succeeded'),
            ]);
        }catch (\Exception $e){
            return response()->json([
                'status'  => false,
                'message' => trans('admin::lang.delete_failed') .$e->getMessage(),
            ]);
        }
    }
}
